//
//  VCOfBeginDoTest.m
//  LCOnePsychology
//
//  Created by li cheng on 16/9/7.
//  Copyright © 2016年 li cheng. All rights reserved.
//

#import "VCOfBeginDoTest.h"
#import "BaseTableView.h"
#import "MJMacro.h"
#import "BaseView.h"
#import "Masonry.h"
#import "TVCellOfBeginDoTest.h"
#import "UIImageView+WebCache.h"
#import "ZWYNetTool.h"
#import "RootClassOfBeginDoTest.h"
#import "DataOfBeginDoTest.h"
#import "UserOfDataBeginDoTest.h"
#import "VCOfDoingTest.h"
#import "VCOfLogining.h"
#import "Masonry.h"
@interface VCOfBeginDoTest ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, weak) IBOutlet UIView *tableViewHeaderViewOfBeginDoTest;
@property (weak, nonatomic) IBOutlet UIImageView *coverImageView;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UILabel *contentLabel;
@property (weak, nonatomic) IBOutlet UILabel *viewnumLabel;
@property (nonatomic, strong) BaseTableView *tableViewOfBeginDoTest;
@property (nonatomic, strong) RootClassOfBeginDoTest *rootClassOfBeginDoTest;
@property (nonatomic, assign) CGSize keyboardSize;
@property (nonatomic, strong) UIView *viewOfBackground;
@property (nonatomic, strong) UITextView *textView;
@end

@implementation VCOfBeginDoTest

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 创建 tableView
    [self createTableView];
    // 创建 barView
    [self createBarView];
    // 给键盘注册通知
    [self registerForKeyboardNotifications];
    // 创建 回复
    [self createReply];
}
#pragma 给键盘注册通知
- (void)registerForKeyboardNotifications
{
    // 给键盘出现通知添加方法选择器
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
    // 给键盘隐藏添加方法选择器
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardDidHideNotification object:nil];
}
#pragma mark - 给键盘出现通知添加方法选择器
- (void) keyboardWasShown:(NSNotification *)notif
{
    NSDictionary *info = [notif userInfo];
    NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    _keyboardSize = [value CGRectValue].size;
    NSLog(@"%f", _keyboardSize.height);
    ///keyboardWasShown = YES;
    
    _viewOfBackground.frame = CGRectMake(0, SCREEN_HEIGHT - _keyboardSize.height - 200, SCREEN_WIDTH, 200);
}
#pragma mark - 给键盘隐藏添加方法选择器
- (void) keyboardWasHidden:(NSNotification *)notif
{
    NSDictionary *info = [notif userInfo];
    NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    _keyboardSize = [value CGRectValue].size;
    // keyboardWasShown = NO;
    _viewOfBackground.frame = CGRectMake(0, -200, SCREEN_WIDTH, 200);
}
#pragma mark - 创建评论的输入框
- (void)createReply{
    self.viewOfBackground = [[UIView alloc] initWithFrame:CGRectMake(0, -200, SCREEN_WIDTH, 200)];
    // 放弃回复 button
    UIButton *buttonOfResignReply = [[UIButton alloc] initWithFrame:CGRectMake(10, 10, 40, 40)];
    [buttonOfResignReply setTitle:@"✖️" forState:UIControlStateNormal];
    [buttonOfResignReply addTarget:self action:@selector(giveUpReply:) forControlEvents:UIControlEventTouchUpInside];
    [self.viewOfBackground addSubview:buttonOfResignReply];
    // label 评论给
    UILabel *labelOfComments = [[UILabel alloc] init];
    labelOfComments.text = @"评论";
    [self.viewOfBackground addSubview:labelOfComments];
    [labelOfComments mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.viewOfBackground).offset(0);
        make.width.mas_offset(60);
        make.height.mas_offset(20);
        make.top.equalTo(self.viewOfBackground).offset(20);
    }];
    // 回复 button
    UIButton *buttonOfReply = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 50, 10, 40, 40)];
    [buttonOfReply setTitle:@"✔️" forState:UIControlStateNormal];
    [buttonOfReply addTarget:self action:@selector(sureReply:) forControlEvents:UIControlEventTouchUpInside];
    [self.viewOfBackground addSubview:buttonOfReply];
    // 输入的视图
    self.textView = [[UITextView alloc] init];
    [self.viewOfBackground addSubview:_textView];
    [self.textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.viewOfBackground).offset(15);
        make.right.equalTo(self.viewOfBackground).offset(-15);
        make.bottom.equalTo(self.viewOfBackground).offset(-15);
        make.height.mas_offset(120);
    }];
    self.viewOfBackground.backgroundColor = [UIColor colorWithRed:0.93 green:0.93 blue:0.93 alpha:1.00];
    [self.view addSubview:_viewOfBackground];
}
#pragma mark - 放弃回复按钮的方法实现
- (void)giveUpReply:(UIButton *)button{
     [_textView resignFirstResponder];
}
#pragma mark - 确认回复
- (void)sureReply:(UIButton *)button{
//    NSLog(@"%@", _textView.text);
    [ZWYNetTool POST:@"http://yiapi.xinli001.com/yi/post-test-comment.json?key=18ee0593a01c07f71d28fa936d671457&_platform=ios&_version=4.0" andBody:[NSString stringWithFormat:@"{\"test_id\":\"%@\",\"token\":\"0d4eeb8732f9ae2c73401002570ceb93\",\"content\":\"%@\"}", _myID, _textView.text] andBodyStyle:ZWYBodyString andHeader:@{@"Content-Type":@"application/json"} andResponse:ZWYJSON andSuccessBlock:^(id result) {
        NSLog(@"%@", result);
        [self.tableViewOfBeginDoTest reloadData];
         [_textView resignFirstResponder];
    } andFailureBlock:^(NSError *error) {

    }];
}
#pragma mark - 数据处理
- (void)handleData{
    NSString *stringURL = [NSString stringWithFormat:@"http://yiapi.xinli001.com/yi/test-comment-list.json/?test_id=%@&limit=10&offset=0&key=e110509c8317557ef50ce777d107f4b3&v=1&_platform=android&_version=4.0&evn=1&sign=99730864ed132ae4e883b553b0b1e6f5&token=0d4eeb8732f9ae2c73401002570ceb93", _myID];
    [ZWYNetTool GET:stringURL andBody:nil andHeader:nil andResponse:ZWYJSON andSuccessBlock:^(id result) {
        _rootClassOfBeginDoTest = [RootClassOfBeginDoTest modelDic:result];
        [self handleData];
        [self.tableViewOfBeginDoTest reloadData];
    } andFailureBlock:^(NSError *error) {

    }];
}
#pragma 属性的 set 方法
- (void)setMyID:(NSString *)myID{
    _myID = myID;
    // 数据处理
    [self handleData];
}
#pragma 属性的 set 方法
- (void)setCoverString:(NSString *)coverString{
    _coverString = coverString;
    // 这个是我建立的, 直接和vc关联的 TVCell 的 xib 所以要实行这个方法
    [[NSBundle mainBundle] loadNibNamed:@"TableViewHeaderViewOfBeginDoTest" owner:self options:nil];
    [self.coverImageView sd_setImageWithURL:[NSURL URLWithString:_coverString] placeholderImage:[UIImage imageNamed:@"JustAMoment"]];
}
- (void)setTitleString:(NSString *)titleString{
    _titleString = titleString;
   self.titleLabel.text = _titleString;
}
- (void)setContentString:(NSString *)contentString{
    _contentString = contentString;
     self.contentLabel.text = _contentString;
}
- (void)setViewnumString:(NSString *)viewnumString{
    _viewnumString = viewnumString;
    self.viewnumLabel.text =_viewnumString;
}
#pragma mark - 创建 tableView
- (void)createTableView{
    self.tableViewOfBeginDoTest = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 49) style:UITableViewStyleGrouped];
    self.tableViewOfBeginDoTest.backgroundColor = [UIColor colorWithWhite:0.922 alpha:1.000];
    [self.view addSubview:_tableViewOfBeginDoTest];
    self.tableViewOfBeginDoTest.delegate = self;
    self.tableViewOfBeginDoTest.dataSource = self;
    [self.tableViewOfBeginDoTest registerNib:[UINib nibWithNibName:@"TVCellOfBeginDoTest" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"TVCellOfBeginDoTest"];
    self.tableViewHeaderViewOfBeginDoTest.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT * 0.7);
    self.tableViewOfBeginDoTest.tableHeaderView = _tableViewHeaderViewOfBeginDoTest;
}
#pragma mark - tableView 代理方法 row 数量的确定
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _rootClassOfBeginDoTest.data.count;
}
#pragma mark - row 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return SCREEN_HEIGHT * 0.2;
}
#pragma mark - tableView 代理方法 cell 的赋值
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TVCellOfBeginDoTest *cell = [tableView dequeueReusableCellWithIdentifier:@"TVCellOfBeginDoTest" forIndexPath:indexPath];
    [cell.avatarImageView sd_setImageWithURL:[NSURL URLWithString:_rootClassOfBeginDoTest.data[indexPath.row].user.avatar] placeholderImage:[UIImage imageNamed:@"JustAMoment"]];
    cell.avatarImageView.layer.cornerRadius = 20;
    cell.avatarImageView.clipsToBounds = YES;
    cell.nicknameLabel.text = _rootClassOfBeginDoTest.data[indexPath.row].user.nickname;
    cell.createdLabel.text = _rootClassOfBeginDoTest.data[indexPath.row].created;
    cell.contentLabel.text = _rootClassOfBeginDoTest.data[indexPath.row].content;
    return cell;
}
#pragma mark - tableView 代理 分区头的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 64;
    } else {
        return 0;
    }
}
#pragma mark - 自定义分区头
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
    UIView *grayView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 20)];
    [headerView addSubview:grayView];
    UILabel *labelOfCommentNumber = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH, 43)];
    labelOfCommentNumber.backgroundColor = [UIColor whiteColor];
    labelOfCommentNumber.text = [NSString stringWithFormat:@"      评论  (%ld)", _rootClassOfBeginDoTest.data.count];
    [headerView addSubview:labelOfCommentNumber];
    return headerView;
    
}
#pragma mark - 创建下面的 barView
- (void)createBarView{
    BaseView *barView = [[BaseView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - 49, SCREEN_WIDTH, 49)];
    barView.backgroundColor = [UIColor colorWithRed:0.21 green:0.69 blue:0.46 alpha:0.10];
    [self.view addSubview:barView];
    // 添加返回的 button
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeSystem];
    backButton.frame = CGRectMake(30, 0, 44, 44);
    if (IS_IPHONE_5) {
        backButton.frame = CGRectMake(10, 0, 44, 44);
    }
    [backButton setTitle:@" 🔙 " forState:UIControlStateNormal];
    [backButton setTitleColor:[UIColor colorWithRed:0.21 green:0.69 blue:0.46 alpha:1.00] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backVC:) forControlEvents:UIControlEventTouchUpInside];
    [barView addSubview:backButton];
    // 添加回复的 button
    UIButton *replyButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [barView addSubview:replyButton];
    [replyButton addTarget:self action:@selector(reply:) forControlEvents:UIControlEventTouchUpInside];
    [replyButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(barView);
        make.height.mas_offset(30);
        make.width.mas_offset(200);
    }];
    [replyButton setTitle:@"✏️ 写评论..." forState:UIControlStateNormal];
    [replyButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 80)];
    // 设置边界弧度
    [replyButton.layer setCornerRadius:5];
    // 设置边界的宽度
    [replyButton.layer setBorderWidth:1];
    // 设置按钮的边界颜色
    UIColor *coloroo = [UIColor colorWithRed:0.008 green:0.008 blue:0.004 alpha:1.000];
    [replyButton.layer setBorderColor:coloroo.CGColor];
    //  创建分享的按钮
    UIButton *shareButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [shareButton setImage:[UIImage imageNamed:@"Share_32"] forState:UIControlStateNormal];
    [barView addSubview:shareButton];
    [shareButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(barView).offset(10);
        if (IS_IPHONE_5) {
            make.right.equalTo(barView).offset(-15);
        } else {
            make.right.equalTo(barView).offset(-30);
        };
        make.width.mas_offset(20);
        make.height.mas_offset(20);
    }];
    
    [shareButton setTintColor:[UIColor blackColor]];
}
#pragma mark - 回复的功能实现
- (void)reply:(UIButton *)button{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *user_id = [user objectForKey:@"user_id"];
    if (user_id){
        // textView 变成第一响应者
        [_textView becomeFirstResponder];
    } else {
        // 跳转到登录界面
        VCOfLogining *vcOfLogining = [[VCOfLogining alloc] init];
        UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:vcOfLogining];
        [self presentViewController:navi animated:YES completion:^{
            
        }];
    }
}
#pragma mark - 点击 <开始测试> 按钮的实现方法
- (IBAction)doTest:(id)sender {
    VCOfDoingTest *vcOfDoingTest = [[VCOfDoingTest alloc] initWithNibName:@"VCOfDoingTest" bundle:[NSBundle mainBundle]];
    vcOfDoingTest.myID = _myID;
    vcOfDoingTest.rootClassOfBeginDoTest = _rootClassOfBeginDoTest;
    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:vcOfDoingTest];
    [self presentViewController:navi animated:YES completion:^{
        
    }];
}
#pragma mark - 返回按钮的实现方法
- (void)backVC:(UIButton *)button{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
#pragma mark - 其他, 内存警告问题
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
